<?php
define('IN_MEDIA',true);
require_once 'includes/debug.php';
include('includes/config.php');
include('includes/functions.php');
global $media_ID;
$isLoggedIn = m_checkLogin();
if (!$isLoggedIn && !$_GET['showcomment']) die("<p style='margin-top:40px;color:#999999'><center><b>Bạn chưa đăng nhập</b></center></p>");
if ($_GET['showcomment'] && $_GET['media_id'] && $_GET['pg'] ) {
	$id = (int)$_GET['media_id'];
//	$addp = 'javascript:return comment_check_values(); document.comment.submit();';	
//	if (!$isLoggedIn){
//				$addp = 'javascript:return alert("Bạn cần đăng nhập để Viết cảm nhận")';
//	}
//	
//		$writeComment	=	" <div id='comment_loading' style='display:none'></div>
//                                <div class='comment_box'>
//                                  <textarea name='comment_content' rows='5' id='comment_content' style='width:465px;height:50px;background:#141415;color:#999999;border:#000000 solid 1px;'></textarea> 
//                                </div>
//							<div class='center-form1'> 
//                            <a class='addFriend commentClick' onClick='$addp' style='float: none;margin: 10px 0 0 1px;width: 100px'>Gửi bình luận</a>
//                            <p class='comment_error'></p>
//                            </div>";
//		
	$media_ID	=	$id;
	
	$q = $mysql->query("SELECT * FROM ".$tb_prefix."comment WHERE comment_media_id = '".$id."' ORDER BY comment_time ASC");
	$total = $mysql->num_rows($q);
	$pg = $_GET['pg'];
	$m_per_page = 10;
	// QUERY SQL
	if (!$pg) $pg = 1;
	$sql = "SELECT * FROM ".$tb_prefix."comment WHERE comment_media_id =".$id." ORDER BY comment_time DESC LIMIT ".(($pg-1)*$m_per_page).",".$m_per_page;
	$query = $mysql->query($sql);
	$link = $mainURL."/comment.php?showcomment=1&media_id=".$id."&pg=";	
	if ($mysql->num_rows($query)) {		
		while ($r = $mysql->fetch_array($query)) {
            $del = '';
			$class = (fmod($i,2) == 0)?'comment_1':'comment_2';
			$content = m_emotions_replace(m_text_tidy($r['comment_content'],1));
			
			$comment_CLASS		=	$class;
			$comment_poster_ID	=	$r['comment_poster'];
			$comment_poster		=	m_get_data('USER',$comment_poster_ID);
			$comment_poster_URL	=	url_link($comment_poster_ID,$comment_poster,'User');
			$comment_TIME		=	date('d-m-Y g:i:s a',$r['comment_time']);
			//check comment_TIME vs current_time
			$commentTime = strtotime($comment_TIME);
			$currentTime = strtotime("now");
			
			$diffTime = $currentTime-$commentTime;
			$dayDiffTime = (int)($diffTime / 86400);

                        
			if($dayDiffTime < 1) {
				//$dayDiffTime = $diffTime->format("%d");
				$hourDiffTime = (int)($diffTime / 3600);
				$minuteDiffTime = (int)($diffTime / 60);
				//$sDiffTime = $diffTime->format("%s");
			}
			//debug($minuteDiffTime);
			$comment_CONTENT	=	$content;
			$comment_ID			=	$r['comment_id'];
			$login_ID = $_SESSION['user_id'];
			
			/*
			 * check xem user đã like hay chưa.
			 *  
			 */
            $checkLike = 0;
            if($login_ID != '') {
                $q = $mysql->query("SELECT * FROM ".$tb_prefix."post WHERE post_media_id = ". $comment_ID . " AND post_poster_id = ". $login_ID);
                if($mysql->num_rows($q)) {
                    $checkLike = 1;
                }
            }
			
			$s = $mysql->fetch_array($mysql->query("SELECT COUNT(*) as sumLike FROM ". $tb_prefix . "post WHERE post_media_id =". $comment_ID));
			$sumLike = $s['sumLike'];
			$checkOwer = 0;
			
			$users = $mysql->query("SELECT p.post_poster_id, u.user_name  FROM ". $tb_prefix . "post AS p LEFT JOIN ". $tb_prefix . "user AS u ON p.post_poster_id = u.user_id WHERE p.post_media_id =" . $comment_ID . " AND p.post_type=2 ORDER BY post_time ASC");
			$listuser=array();
			$view_pages = ceil($total,$m_per_page);	
			$avatar	 =  $mysql->fetch_array($mysql->query("SELECT user_avatar FROM ".$tb_prefix."user WHERE user_id = '".$comment_poster_ID."'"));
			$avatar = $avatar[0];
            if($_SESSION['user_id']) {   
				if($_SESSION['user_id'] == $r['comment_poster']) {
					$del	=	"- <a href='#Delete' onClick='return comment_delete($media_ID,$comment_ID)'><b>Xóa</b></a>";
				}
				if(m_check_level($_SESSION['user_id']) == 3) {
					$del	=	"- <a href='#Delete' onClick='return comment_delete($media_ID,$comment_ID)'><b>Xóa</b></a>";
				}
				if(m_check_level($_SESSION['user_id']) == 2) {
					$del	=	"- <a href='#Delete' onClick='return comment_delete($media_ID,$comment_ID)'><b>Xóa</b></a>";
				}				
            }
				if(m_user_level($comment_poster_ID) == "Admin") {
					$comment_poster	= "<font color=#CC0000 >".$comment_poster."</font>";
				}
				if(m_user_level($comment_poster_ID) == "Moderator") {
					$comment_poster	= "<font color=#FF9900 >".$comment_poster."</font>";
				}
			$spamwords = "/(T O P D J V N|TOPDJVN|.com|.net|.org|.vn|.info|c o m|n e t|i n f o|c@m|[.](\s)C0M|C[(][)]M|C [(][)] M)/i";
				
				//$comment_CONTENT1 = preg_replace('/\s/', '', $comment_CONTENT);

			
			//$comment_CONTENT1 = preg_replace('/\s{2,}/', ' ', $comment_CONTENT);
			if (preg_match($spamwords, $comment_CONTENT)) {

				$comment_CONTENT = "Hay!";
			}
			
/*			else if(preg_match("/[.]net/i", $comment_CONTENT))
			{
				$comment_CONTENT = "hay";
			}
			else if(preg_match("/[.]org/i", $comment_CONTENT))
			{
				$comment_CONTENT = "hay";
			}
			else if(preg_match("/[.]vn/i", $comment_CONTENT))
			{
				$comment_CONTENT = "good";
			}
			else if(preg_match("/[.](\s)c(\s)o(\s)m/i", $comment_CONTENT))
			{
				$comment_CONTENT = "good";
			}
			else if(preg_match("/[.](\s)n(\s)e(\s)t/i", $comment_CONTENT))
			{
				$comment_CONTENT = "good";
			}
			else if(preg_match("/[.](\s)v(\s)n/i", $comment_CONTENT))
			{
				$comment_CONTENT = "good";
			}
			else if(preg_match("/[.](\s)i(\s)n(\s)f(\s)o/i", $comment_CONTENT))
			{
				$comment_CONTENT = "good";
			}	
*/			
			else {
				$comment_CONTENT = $comment_CONTENT;
			}
            
            /**
            *Phần like cho comment sẽ được merge vào trong chuỗi $comment_HTML
            */
            $like = '';
            if($login_ID) {
                if($checkLike == 0) {
                        $like       = "<span class='like_comment' id='like_comment_{$comment_ID}'> <a href='#' onclick='return like_comment($comment_ID, $login_ID, 2)'>Thích</a></span>";
                } else {
                        $like       = "<span class='like_comment' id='like_comment_{$comment_ID}'> <a href='#' onclick='return unlike_comment($comment_ID, $login_ID, 2)'>Không thích</a></span>";
                }   
            }
            $like  .=  "<a id='sumlike_{$comment_ID}_2' class='countLikeComment sumlike'>
                            <span class='countLC'>$sumLike</span>
                        </a>";
			$comment_HTML		.=	"<li id='comment_$comment_ID'>
	                           		 	<p class='left'><span class='time'><img src='$avatar' width='40px' height='40px' border='1px' alt='DJ MATXAC' /></span></p><p class='title1'><a href='$comment_poster_URL'>$comment_poster</a> $comment_CONTENT</p>";
	        if($dayDiffTime > 1) {
	        	$comment_HTML 	.= "<p class='user'>$comment_TIME - $like người thích  $del</p>";
	        } else {
	        	if($hourDiffTime < 1) {
	        		if($minuteDiffTime < 1 ) {
	        			$comment_HTML 	.= "<p class='user'> vài giây trước - $like người thích  $del</p>";
	        		} else {
	        			$comment_HTML 	.= "<p class='user'> $minuteDiffTime phút trước - $like người thích  $del</p>";
	        		}
	        		
	        	} else {
	        		$comment_HTML 	.= "<p class='user'> cách đây $hourDiffTime h - $minuteDiffTime phút trước - $like người thích  $del</p>";
	        	}
	        }
            $comment_HTML 	   .=  "<div class='clear'></div></li>";
		}
	}
	else $comment_HTML = ' <li id="emptyComment">
                           		<p class="title">Chưa có bình luận nào !</p>
							</li>';
    $q = $mysql->fetch_array($mysql->query("SELECT COUNT(*) as 'sumComment' FROM ".$tb_prefix."comment WHERE comment_media_id = '".$id."'"));
    $rt['sumComment'] = $q['sumComment'];
    $rt['comment'] = $comment_HTML;
    echo json_encode($rt);
}
elseif ($_POST['comment'] && $_POST['media_id'] && $_POST['comment_content']) {
	$warn = '';
	$media_id = (int)$_POST['media_id'];
	$comment_content = substr(stripslashes(trim(urldecode($_POST['comment_content']))),0,255);
    
	if ($comment_content) {
		//$q = $mysql->query("SELECT comment_id FROM ".$tb_prefix."comment WHERE comment_media_id = '".$media_id."' AND comment_content = '".$comment_content."' AND comment_poster = '".$_SESSION['user_id']."'");
		$mysql->query("DELETE FROM ".$tb_prefix."manage WHERE manage_timeout < '".NOW."'");
		$q = $mysql->query("SELECT manage_timeout FROM ".$tb_prefix."manage WHERE manage_type = 'Comment' AND manage_user = '".$_SESSION['user_id']."' AND manage_media = '".$media_id."' AND manage_timeout >= '".NOW."'");
		//$r = $mysql->fetch_array($q);
		if (!$mysql->num_rows($q) || m_check_level($_SESSION['user_id'])) {
			if(preg_match('/[\']/', $comment_content)){
                $rt['status'] = 'fail';
                $rt['msg'] = "Không được sử dụng ký tự '";
			} else {
                $time = time();
                if ($mysql->query("INSERT INTO ".$tb_prefix."comment (comment_media_id,comment_poster,comment_content,comment_time) VALUES ('".$media_id."','".$_SESSION['user_id']."','".$comment_content."','$time')")) {
                    $commentID = $mysql->insert_id();
                    if (!m_check_level($_SESSION['user_id'])) 
                        $mysql->query("INSERT INTO ".$tb_prefix."manage VALUES ('Comment','".$_SESSION['user_id']."','".$media_id."','".($time + 60*2)."')");
                    
                    /**
                     * Dữ liệu đẩy đến notification đưa vào đây 
                     */
                    $u_action_id = $_SESSION['user_id'];
                    $u_action_name = m_get_data('USER',$_SESSION['user_id']);
                    $rs = $mysql->fetch_array($mysql->query("SELECT m_poster, m_title FROM ".$tb_prefix."data WHERE m_id=$media_id"));
                    $ownerMedia = $rs['m_poster'];
                    $media_name = $rs['m_title'];
                    if($ownerMedia != $u_action_id)
                        $mysql->query("INSERT INTO ".$tb_prefix."noti(obj_id,u_id, u_action_id, u_action_name, m_id, m_name, noti_type, noti_stt, noti_time) VALUES ('$commentID','$ownerMedia', '$u_action_id', '$u_action_name', '$media_id', '$media_name',1,1,'$time')");
                    $rs = $mysql->query("(SELECT comment_poster as 'u_id', comment_time as 'time' 
                                            FROM ".$tb_prefix."comment 
                                            WHERE comment_media_id = $media_id AND comment_poster <> $ownerMedia AND comment_poster <> $u_action_id)
                                          UNION DISTINCT
                                          (SELECT post_poster_id as 'u_id', post_time as 'time'
                                            FROM ".$tb_prefix."post
                                            WHERE post_media_id = $media_id AND post_poster_id <> $ownerMedia AND post_poster_id <> $u_action_id)
                                          ORDER BY time DESC LIMIT 0,15");
                    while($r = $mysql->fetch_array($rs)) {
                        $mysql->query("INSERT INTO ".$tb_prefix."noti(obj_id, u_id, u_action_id, u_action_name, m_id, m_name, noti_type, noti_stt, noti_time) VALUES ('$commentID','{$r['u_id']}', '$u_action_id', '$u_action_name', '$media_id', '$media_name',1,1,'$time')");
                    }
                    /**
                     * Lấy dữ liệu về user và comment đưa về client
                     */
                    $content = m_emotions_replace(m_text_tidy($comment_content,1));
                    $comment_CLASS		=	$class;
                    $comment_poster_ID	=	$_SESSION['user_id'];
                    $comment_poster		=	m_get_data('USER',$comment_poster_ID);
                    $comment_poster_URL	=	url_link($comment_poster_ID,$comment_poster,'User');
                    $comment_TIME		=	date('d-m-Y',$time);
                    $comment_CONTENT	=	$content;
                    $comment_ID			=	$media_id;
                    $view_pages = ceil($total,$m_per_page);	
                    $avatar	 =  $mysql->fetch_array($mysql->query("SELECT user_avatar FROM ".$tb_prefix."user WHERE user_id = '".$comment_poster_ID."'"));
                    $avatar = $avatar[0];
                    $del	=	"- <a href='#Delete' onClick='return comment_delete($media_id,$commentID)'><b>Xóa</b></a>";
                    if(m_user_level($comment_poster_ID) == "Admin") {
                        $comment_poster	= "<font color=#CC0000 >".$comment_poster."</font>";
                    }
                    if(m_user_level($comment_poster_ID) == "Moderator") {
                        $comment_poster	= "<font color=#FF9900 >".$comment_poster."</font>";
                    }
                    $spamwords = "/(T O P D J V N|TOPDJVN|.com|.net|.org|.vn|.info|c o m|n e t|i n f o|c@m|[.](\s)C0M|C[(][)]M|C [(][)] M)/i";
                    if (preg_match($spamwords, $comment_CONTENT)) {
                        $comment_CONTENT = "Hay!";
                    } else {
                        $comment_CONTENT = $comment_CONTENT;
                    }
                    
                    /**
                     *Phần like cho comment sẽ được merge vào trong chuỗi $rt['msg']  
                     */
                    $like   = "<span class='like_comment' id='like_comment_$commentID'> <a href='#' onclick='return like_comment($commentID, $u_action_id, 2)'>Thích</a></span>";
                    $like  .=  "<a id='sumlike_{$commentID}_2' class='countLikeComment sumlike'>
                                    <span class='countLC'>0</span>
                                </a>";
                    $rt['status'] = 'success';
                    $rt['msg']      =	"<li id='comment_$commentID'>
                                            <p class='left'><span class='time'><img src='$avatar' width='40px' height='40px' border='1px' alt='DJ MATXAC' /></span></p>
                                            <p class='title1'><a href='$comment_poster_URL'>$comment_poster</a> $comment_CONTENT</p><p class='user'>2 giây trước ' $like $del</p>
                                        </li>";
                } else {
                    $rt['status'] = 'fail';
                    $rt['msg'] = "Có lỗi xảy ra, vui lòng thử lại !";
                }
            }
		} else {
			$r = $mysql->fetch_array($q);
            $rt['status'] = 'fail';
			$rt['msg'] = "Bạn cần chờ thêm <b>".($r['manage_timeout'] - NOW)."</b> giây nữa mới có thể viết tiếp cảm nhận";
		}
	} else {
        $rt['status'] = 'fail';
        $rt['msg'] = "Bạn chưa nhập cảm nhận";
    }
    
    echo json_encode($rt);
}
elseif ($_POST['delete'] && is_numeric($_POST['comment_id']) && is_numeric($_POST['media_id'])) {
	$comment_id = (int)$_POST['comment_id'];
	$media_id = (int)$_POST['media_id'];
    $q = $mysql->query("SELECT * FROM ".$tb_prefix."comment WHERE comment_media_id='$media_id' AND comment_id='$comment_id'");
    if($mysql->num_rows($q)) {
        $r = $mysql->fetch_array($q);
        if($_SESSION['user_id'] == $r['comment_poster'] OR m_check_level($_SESSION['user_id']) == 3 OR m_check_level($_SESSION['user_id']) == 2) {
            if($mysql->query("DELETE FROM ".$tb_prefix."comment WHERE comment_media_id = '".$media_id."' AND comment_id = '".$comment_id."'")) {
                if($mysql->query("DELETE FROM ".$tb_prefix."noti WHERE obj_id IN (SELECT post_id FROM ".$tb_prefix."post WHERE post_media_id = $comment_id AND post_type=2) AND noti_type=3")) {
                    if($mysql->query("DELETE FROM ".$tb_prefix."post WHERE post_media_id=$comment_id AND post_type=2")) {
                        if($mysql->query("DELETE FROM ".$tb_prefix."noti WHERE obj_id = '$comment_id' AND noti_type=1")) {
                            $rt['status'] = 'success';
                        } else {
                            $rt['status'] = 'fail';
                            $rt['msg'] = 'Có lỗi xảy ra, vui lòng thử lại !';   
                        }
                    } else {
                        $rt['status'] = 'fail';
                        $rt['msg'] = 'Có lỗi xảy ra, vui lòng thử lại !';   
                    }
                } else {
                    $rt['status'] = 'fail';
                    $rt['msg'] = 'Có lỗi xảy ra, vui lòng thử lại !';   
                }
            } else {
                $rt['status'] = 'fail';
                $rt['msg'] = 'Có lỗi xảy ra, vui lòng thử lại !';
            }
        } else {
            $rt['status'] = 'fail';
            $rt['msg'] = 'Bạn không có quyền xóa bình luận, vui lòng thử lại !';
        }
    } else {
        $rt['status'] = 'fail';
        $rt['msg'] = 'Bình luận không chính xác, vui lòng thử lại !';
    }
    echo json_encode($rt);
}
?>